package threadLock.LongAdder;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.LongAccumulator;

/**
 * LongAdder类是LongAccumulator类的派生类
 * 后者功能性更强 可以自定义实现的计数功能
 */
public class LongAccumulatorTest {
    //创建自定义累加器
    private static volatile LongAccumulator longAcc = new LongAccumulator(Long::sum,0);

    public static void main(String[] args) {
        int max = 8;
        Semaphore semaphore = new Semaphore(max);
        CountDownLatch countDownLatch = new CountDownLatch(max);
        for (int i = 1; i < max+1; i++) {
            int a = i;
            Thread thread = new Thread(()->{
                try {
                    semaphore.acquire();
                    longAcc.accumulate(a);
                    System.out.println("线程: "+Thread.currentThread().getName()+"累加结果: "+longAcc.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            },""+i);
            thread.start();
        }
        countDownLatch.countDown();
        System.out.println("(1+n)*n/2 " + (1 + max) * (max / 2));
    }
}

